<template>
  <div class="register-container">
    <el-card class="register-card">
      <template #header>
        <div class="card-header">
          <el-button
              class="back-button"
              icon="ArrowLeft"
              link
              @click="$router.back()">
            返回
          </el-button>
          <h2>用户注册</h2>
        </div>
      </template>

      <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="rules"
          label-position="top">

        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="registerForm.username"
              prefix-icon="User"
              placeholder="请输入用户名">
          </el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
              v-model="registerForm.phone"
              prefix-icon="Cellphone"
              placeholder="请输入手机号">
          </el-input>
        </el-form-item>

        <el-form-item label="设置密码" prop="password">
          <el-input
              v-model="registerForm.password"
              prefix-icon="Lock"
              type="password"
              placeholder="请设置6-20位密码"
              show-password>
          </el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="registerForm.confirmPassword"
              prefix-icon="Lock"
              type="password"
              placeholder="请再次输入密码"
              show-password>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="registerForm.agreement">
            我已阅读并同意
            <el-link type="primary" :underline="false">《用户协议》</el-link>
            和
            <el-link type="primary" :underline="false">《隐私政策》</el-link>
          </el-checkbox>
        </el-form-item>

        <el-button
            type="primary"
            class="register-button"
            :loading="loading"
            @click="handleRegister">
          注册
        </el-button>

        <div class="login-link">
          已有账号？
          <el-link
              type="primary"
              :underline="false"
              @click="$router.push('/login')">
            立即登录
          </el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from "axios";
import qs from 'qs'

const BASE_URL = 'http://localhost:8080'  // 替换为你的实际后端地址

const router = useRouter()
const registerFormRef = ref(null)
const loading = ref(false)

const registerForm = ref({
  username: '',
  phone: '',
  password: '',
  confirmPassword: '',
  agreement: false
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3-20位之间', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '用户名只能包含字母、数字、下划线和横线', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请设置密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6-20位之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const handleRegister = async () => {
  if (!registerFormRef.value) return

  if (!registerForm.value.agreement) {
    ElMessage.warning('请阅读并同意用户协议和隐私政策')
    return
  }

  // 验证表单
  await registerFormRef.value.validate(async (valid) => {
    if (!valid) {
      return
    }

    loading.value = true

    // 构造注册数据，移除确认密码和协议字段
    const registerData = {
      username: registerForm.value.username,
      phone: registerForm.value.phone,
      password: registerForm.value.password
    }

    axios.post(`${BASE_URL}/v1/register/add`, registerData, {
      headers: {
        'Content-Type': 'application/json'
      },
      withCredentials: true
    })
        .then((response) => {
          if (response.data.code === 2000) {
            ElMessage.success('注册成功')
            router.push('/login')
          } else {
            ElMessage.error(response.data.msg || '注册失败')
          }
        })
        .catch((error) => {
          console.error('注册失败:', error)
          if (error.response) {
            ElMessage.error(error.response.data.msg || '注册失败')
          } else {
            ElMessage.error('注册失败，请稍后重试')
          }
        })
        .finally(() => {
          loading.value = false
        })
  })
}
</script>

<style scoped>
.register-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.register-card {
  width: 400px;
}

.card-header {
  text-align: center;
  position: relative;
}

.card-header h2 {
  margin: 0;
  color: #333;
}

.register-button {
  width: 100%;
  margin-bottom: 20px;
}

.login-link {
  text-align: center;
}

.back-button {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  font-size: 14px;
}

@media (max-width: 768px) {
  .register-card {
    width: 90%;
    margin: 0 20px;
  }
}
</style>